package com.suncky.frame.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.ColorRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;

import com.gyf.immersionbar.ImmersionBar;
import com.suncky.frame.ActivityManager;
import com.suncky.frame.R;
import com.suncky.frame.dialog.LoadingDialog;
import com.suncky.frame.utils.LogUtils;
import com.suncky.frame.utils.SingleClickManager;
import com.suncky.frame.widget.SlideBackLayout;

import java.lang.reflect.Method;

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    private LoadingDialog loadingPop;
    private DefaultTitleHelper defaultTitleHelper;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(getScreenOrientation());
        ActivityManager.getInstance().attach(this);
        setContentView(R.layout.layout_base_title_activity);
        initContentView();
        initDefaultTitle();
        initView(savedInstanceState);
        initView();
        initData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().detach(this);
        if (defaultTitleHelper != null) {
            defaultTitleHelper.detach();
        }
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        //在8.0系统系统中，当activity为透明时，固定activity的方向会抛出 Only fullscreen activities can request orientation 异常
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
//            LogUtils.i("avoid calling setRequestedOrientation when Oreo.");
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    @SuppressLint("PrivateApi")
    private boolean isTranslucentOrFloating(){
        boolean isTranslucentOrFloating = false;
        try {
            int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean)m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    /**
     * @deprecated use {@link #initView(Bundle)} instead
     */
    @Deprecated
    protected void initView() {

    }

    /**
     * 初始化view
     * @param savedInstanceState {@link #onSaveInstanceState(Bundle)} 提供的Bundle数据
     */
    protected void initView(@Nullable Bundle savedInstanceState) {

    }

    /**
     * 初始化数据
     */
    protected void initData() {

    }

    protected void initContentView() {
        FrameLayout viewGroup = findViewById(R.id.view_container);
        View view = getContentView();
        if (view != null) {
            viewGroup.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        }
        //如果activity是全屏状态，不显示状态栏，隐藏状态栏view
        if ((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)
                == WindowManager.LayoutParams.FLAG_FULLSCREEN
                ||(getWindow().getAttributes().systemUiVisibility & View.SYSTEM_UI_FLAG_FULLSCREEN)
                == View.SYSTEM_UI_FLAG_FULLSCREEN
                ||(getWindow().getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_FULLSCREEN)
                == View.SYSTEM_UI_FLAG_FULLSCREEN) {
            findViewById(R.id.status_bar_view).setVisibility(View.GONE);//隐藏状态栏view
        }
        //初始化状态栏
        ImmersionBar.with(this)
                .navigationBarColor(R.color.navigationBarColor)
                .navigationBarDarkIcon(getResources().getBoolean(R.bool.navigationBarDarkIcon))
                .statusBarView(R.id.status_bar_view)
                .statusBarDarkFont(getResources().getBoolean(R.bool.statusBarDarkFont))
                .init();
        if (canSlideOut()) {
            new SlideBackLayout(getContext()).bind();
        }
    }

    protected void initDefaultTitle() {
        defaultTitleHelper = new DefaultTitleHelper();
        defaultTitleHelper.attach(findViewById(R.id.title_base));
        defaultTitleHelper.getLeftImage().setOnClickListener(this);
        defaultTitleHelper.getLeftText().setOnClickListener(this);
        defaultTitleHelper.getRightImage().setOnClickListener(this);
        defaultTitleHelper.getRightText().setOnClickListener(this);
        if (!useDefaultTitle()) {
            defaultTitleHelper.hide();
        }
    }

    @LayoutRes
    protected abstract int getLayoutResId();

    protected View getContentView() {
        if (getLayoutResId() != 0) {
            return getLayoutInflater().inflate(getLayoutResId(), null);
        }
        return null;
    }

    public Context getContext() {
        return this;
    }

    public DefaultTitleHelper getDefaultTitle() {
        return defaultTitleHelper;
    }

    public void setTitle(String title) {
        defaultTitleHelper.setTitle(title);
    }

    public void setTitle(int titleRes) {
        defaultTitleHelper.setTitle(titleRes);
    }

    /**
     * 获取状态栏背景view
     * @return
     */
    public View getStatusBarView() {
        return findViewById(R.id.status_bar_view);
    }

    /**
     * 设置状态栏背景颜色
     * @param colorRes
     */
    public void setStatusBarBackgroundResource(@ColorRes int colorRes) {
        findViewById(R.id.status_bar_view).setBackgroundResource(colorRes);
    }
    /**
     * 设置状态栏背景颜色
     * @param color
     */
    public void setStatusBarBackgroundColor(int color) {
        findViewById(R.id.status_bar_view).setBackgroundColor(color);
    }


    /**
     * 隐藏状态栏view
     */
    public void hideStatusBarView() {
        findViewById(R.id.status_bar_view).setVisibility(View.GONE);
    }

    /**
     * 显示状态栏view
     */
    public void showStatusBarView() {
        findViewById(R.id.status_bar_view).setVisibility(View.VISIBLE);
    }


    /**
     * 显示加载框
     */
    public void showLoadingPop() {
        showLoadingPop(null);
    }

    /**
     * 显示加载框
     * @param title 提示信息
     */
    public void showLoadingPop(String title) {
        if (loadingPop != null) {
            if (loadingPop.isShowing()) {
                loadingPop.dismiss();
            }
        }
        loadingPop = buildLoadingDialog(title);
        loadingPop.show();
    }

    public void dismissLoadingPop() {
        if (loadingPop != null) {
            loadingPop.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (SingleClickManager.isReClick(id)) {
            return;
        }
        onSingledClick(v);
    }

    /**
     * 防重复点击事件响应
     * 防重复点击，需重写此方法，在此方法中执行点击事件
     * @param v
     */
    protected void onSingledClick(View v) {
        int id = v.getId();
        if (id == defaultTitleHelper.getLeftImage().getId()) {
            onDefaultLeftImageClick();
        } else if (id == defaultTitleHelper.getRightText().getId()) {
            onDefaultRightTextClick();
        } else if (id == defaultTitleHelper.getLeftText().getId()) {
            onDefaultLeftTextClick();
        } else if (id == defaultTitleHelper.getRightImage().getId()) {
            onDefaultRightImageClick();
        }
    }

    /**
     * 默认标题栏左侧图标点击事件
     */
    protected void onDefaultLeftImageClick(){
        finish();
    }

    /**
     * 默认标题栏左侧文字点击事件
     */
    protected void onDefaultLeftTextClick(){
        finish();
    }

    /**
     * 默认标题栏右侧文字点击事件
     */
    protected void onDefaultRightTextClick(){

    }

    /**
     * 默认标题栏右侧图标点击事件
     */
    protected void onDefaultRightImageClick(){

    }

    /**
     * 是否使用默认title
     * @return
     */
    protected boolean useDefaultTitle() {
        return true;
    }

    /**
     * 是否可滑动退出
     * @return
     */
    protected boolean canSlideOut() {
        return true;
    }

    /**
     * 固定屏幕方向
     * @return
     */
    protected int getScreenOrientation() {
        return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    /**
     * 构建加载框
     * @param title 提示信息
     * @return
     */
    protected LoadingDialog buildLoadingDialog(String title) {
        return LoadingDialog.with(getContext()).message(title);
    }
}
